﻿//*** Guidance generated code ***//

using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;

using ProjectBase.Core;
using ProjectBase.Core.Web;
using ProjectBase.Mvc;

using Survey.Common;

namespace Survey.Web.Controls
{
    public class StoryListView : ListView
    {
        protected override Table CreateListView()
        {
            return base.CreateListView()
                       .SetCssClassName("story");
        }
        protected override ITableChild CreateBody()
        {
            var body = new TableBody();

            var isOdd = true;
            var rowNumber = 0;
            foreach (var item in Model.ItemsToDisplay)
            {
                body.Add(CreateRowForItem(item, isOdd, rowNumber++));
                body.Add(CreateDescription(item, rowNumber));
                isOdd = !isOdd;
            }

            return body;
        }

        protected override TableCell CreateCellForItem(IItemToDisplay item, ICellDescription cell, int rowNumber, int columnNumber)
        {
            var tableCell = base.CreateCellForItem(item, cell, rowNumber, columnNumber);
            if (columnNumber == 0)
            {
                tableCell
                    .SetCssClassName("title")
                    .SetAttribute(Attr.ColSpan, "2");
            }
            if (columnNumber == 1)
            {
                tableCell = null;
            }
            return tableCell;
        }
        protected virtual ITableRow CreateDescription(IItemToDisplay item, int rowNumber)
        {
            var cell = item.Items
                .Where(i => i.HeaderName.IsEqual("Description"))
                .FirstOrDefault();
            if (cell.IsNull())
            {
                return null;
            }

            var div = new Div();
            foreach (IVisualControl control in CreateCellForItem(item, cell, rowNumber, 0).Controls)
            {
                div.AddControls(control);
            }

            return new TableRow
            {
                new TableCell("description")
                    .SetAttribute(Attr.ColSpan, (item.Items.Count).ToString("N0"))
                    .AddControls(div)
            };
        }
    }
}